﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Clandestine;
using Clandestine.Entities;

namespace JibberJabber
{
    public class PreviewBackground
    {
        private Level level = null;
        private Sprite sprite = null;

        private string levelFilename = "";
        private Texture texture = null;

        private void cleanup()
        {
            if (level != null)
            {
                level.Destroy();
                level = null;
            }
            if (sprite != null)
            {
                sprite.Dispose();
                sprite = null;
            }
        }

        /// <summary>
        /// Not 100% accurate, b/c of the nature of Levels!
        /// (i.e. Entities can make sprites which they don't have
        /// to tell us about.)
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Sprite> TryGetSprites()
        {
            if (sprite != null)
                return new Sprite[] { sprite };
            else if (level != null)
            {
                List<Sprite> list = new List<Sprite>();
                foreach (Entity e in level.Entities.LoadedEntities.Values)
                    if (e.Sprite != null)
                        list.Add(e.Sprite);
                list.AddRange(level.GetMegaTiles());
                return list;
            }
            else
                return new Sprite[] { };
        }

        public void Reload()
        {
            // Ugh, someone disposed our background. :<
            if (level != null)
                level = new Level(levelFilename);
            if (sprite != null)
                sprite = new Sprite(texture);
        }

        public void Clear()
        {
            cleanup();
        }

        public void SetLevel(string filename)
        {
            cleanup();
            this.level = new Level(filename);
            this.levelFilename = filename;
        }

        public void SetBitmap(string bitmapFilename)
        {
            cleanup();
            this.sprite = new Sprite(Texture.GetTexture(bitmapFilename));
            this.texture = this.sprite.GetTexture();
        }
    }
}
